package com.jiang.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;

@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
		 * The doGet method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to get.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String fileName = null;
		try{
			SmartUpload smart = new SmartUpload();
			smart.initialize(super.getServletConfig(), request, response);
			// 获取所有的文件
			smart.upload();
			// 如果直接是使用save(上传到的目录)
			// 生成新的文件名
			fileName = UUID.randomUUID().toString()+"."+smart.getFiles().getFile(0).getFileExt();
			String filePath = super.getServletContext().getRealPath("/upload") +File.separator+ fileName;
			System.out.println(filePath);
			// 如果是使用新文件名，那么使用文件.save(路径+文件名)
			smart.getFiles().getFile(0).saveAs(filePath);
			String result = "{fileName:\""+fileName+"\", saved:"+true+"}";
			System.out.println(result);
			out.println(result);
		}catch(Exception e){
			out.println("{fileName:\""+fileName+"\", saved:"+true+"}");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			this.doGet(request, response);
	}

}
